package cn.qayy.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.qayy.constants.Constant;
import cn.qayy.dao.PlanMapper;
import cn.qayy.dao.TaskMapper;
import cn.qayy.dto.Msg;
import cn.qayy.dto.TaskDTO;
import cn.qayy.dto.TaskTotalDTO;
import cn.qayy.po.Task;
import cn.qayy.po.TaskTotal;
import cn.qayy.service.ITaskService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.ArithUtil;
import cn.qayy.utils.DateUtils;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.StringUtil;

/***
 * @author wangyu
 *
 */
@Service("taskServiceImpl")
public class TaskServiceImpl implements ITaskService {

	@Resource
	private TaskMapper taskMapper;
	
	@Resource
	private PlanMapper planMapper;
	
	@Override
	public PageInfo<Task> selectBy(TaskDTO dto) throws Exception {
		if (dto != null) {
			DownLoadUtil.set("TaskDTO",dto);
			PageHelper.startPage(dto.getPageNumber(),dto.getPageSize());
			
			List<Task> list = taskMapper.selectBy(dto);
			PageInfo<Task> pageInfo = new PageInfo<Task>(list);
			return pageInfo;
		}
		return null;
	}

	@Override
	public int updateByList(List list) {
		return taskMapper.updateByList(list);
	}

	@Override
	public Task selectByID(Integer id) {
		return taskMapper.selectByID(id);
	}

	@Override
	public void insertByList(List<Task> list) {
		taskMapper.insertByList(list);
	}
	
	public List<TaskTotal> selectForTotal(TaskTotalDTO dto) {
		List<TaskTotal> list = taskMapper.selectForTotal(dto);
		return list;
	}

	@Override
	public void persistence(Map<String, List<Uploadable>> map) throws Exception {
		List<Uploadable> listE = map.get("E");
		
		if(listE != null && !listE.isEmpty()) {
			List<Task> list = new ArrayList<Task>();
			for (Uploadable u : listE) {
				TaskDTO dto = (TaskDTO)u;
				Task task = taskMapper.selectByID(StringUtil.parseInt(dto.getId()));
				if(task != null) {
					task.setByDTO(dto);
					Integer taskM1 = StringUtil.parseInt(dto.getTaskM1());
					Integer taskM2 = StringUtil.parseInt(dto.getTaskM2());
					Integer taskM3 = StringUtil.parseInt(dto.getTaskM3());
					float target = taskM1+taskM2+taskM3;
					
					Integer m1 = StringUtil.parseInt(task.getM1());
					Integer m2 = StringUtil.parseInt(task.getM2());
					Integer m3 = StringUtil.parseInt(task.getM3());
					float m = m1+m2+m3;
					
					Integer q = StringUtil.parseInt(task.getQuarterActual());
					
					String tv = Constant.NA;
					if((m1+m2+m3) == 0){
						tv = Constant.NA;
					} else {
						float aa = target/m;
						String a = ArithUtil.format2bit(aa-1);
						float v = StringUtil.parseFloat(a)*100;
						int t = (int)(v);
						tv = t+"%";
					}
					task.setTaskGrowthRate(tv);
					
					String wcv = Constant.NA;
					if((taskM1+taskM2+taskM3) == 0){
						wcv = Constant.NA;
					} else {
						float aa = q/target;
						String a = ArithUtil.format2bit(aa);
						float v = StringUtil.parseFloat(a)*100;
						int t = (int)(v);
						wcv = t+"%";
					}
					task.setCompleteRate(wcv);
					
					list.add(task);
				} else {
					throw new Exception(Constant.FAIL_MSG_ID+"【错误id:"+dto.getId()+"】");
				}
			}
			if(!list.isEmpty()) {
				taskMapper.updateByList(list);
			}
		}
	}
	
	@Override
	public Msg selectInfoBy(TaskDTO dto){
		Msg msg = new Msg();
		Task checkTask = taskMapper.selectInfoBy(dto);
		if(checkTask!=null) {//已在task表中存在不能重复添加
			msg = new Msg(-1,"对应客户、包装、产品、终端QS名已在存在，不能重复添加！");
			return msg;
		}
		
		Map<String,String> lastMap = new HashMap<String,String>();//上个版本参数
		Map<String,String> currentMap = new HashMap<String,String>();//存放当前版本参数
		lastMap.put("client",dto.getClient());
		lastMap.put("page", dto.getPage());
		lastMap.put("product", dto.getProduct());
		lastMap.put("terminalQs",dto.getTerminalQs());
		
		//currentMap=lastMap;
		currentMap.put("client",dto.getClient());
		currentMap.put("page", dto.getPage());
		currentMap.put("product", dto.getProduct());
		currentMap.put("terminalQs",dto.getTerminalQs());
		
		Map<String,String> planRet = planMapper.selectBasisForTask(lastMap);	//从流向表获取基本字段 省份、地市...
		
		if(planRet==null) {
			msg = new Msg(-1,"对应客户、包装、产品、终端QS名必须在流向表中存在，请重新添加！");
			return msg;
		}else {	//能在流向里查询到才继续联想字段
			String currentversion = DateUtils.getCurrentVersion();	//获取当前版本号
			String[] currentMonth = DateUtils.getQuarterMonth(currentversion);	//当前版本季度对应的月份
			String currentYear = DateUtils.getVersionYear(currentversion);
			//获取当前版本的月份
			currentMap.put("m1", currentMonth[0]);
			currentMap.put("m2", currentMonth[1]);
			currentMap.put("m3", currentMonth[2]);
			currentMap.put("year", "20"+String.valueOf(currentYear));
			
			String lastVersion = DateUtils.getQuarterLastVersion(currentversion); //获取上个版本
			String lastYear = DateUtils.getVersionYear(lastVersion);	//上个版本的年份
			String[] lastMonth = DateUtils.getQuarterMonth(lastVersion);	//上一个版本的月份
			//获取上个版本的月份
			lastMap.put("m1", lastMonth[0]);
			lastMap.put("m2", lastMonth[1]);
			lastMap.put("m3", lastMonth[2]);
			lastMap.put("year", "20"+String.valueOf(lastYear));
			Task task = new Task();
			task.setProvince(planRet.get("province"));
			task.setCity(planRet.get("city"));
			task.setCountry(planRet.get("country"));
			task.setMgr(planRet.get("mgr"));
			task.setTerminalType(planRet.get("terminalType"));
			task.setTerminalLevel(planRet.get("terminalLevel"));
			task.setPolicyPrice(planRet.get("atsum"));
			List<Map<String,String>> countRet = planMapper.selectCountForTask(lastMap);
			String actualCount =  planMapper.selectActualForTask(currentMap);//获取当前季度的实际纯销
			task.setQuarterActual(actualCount);
			String count = "0";
			if(countRet.size()>0) {	//上个版本有流向才赋值 上个版本的纯销
				for(Map<String,String> cr : countRet) {
					count = String.valueOf(cr.get("count"));
					if(cr.get("mouth").equals(lastMonth[0])) {	//m1
						task.setM1(count);
					}else if(cr.get("mouth").equals(lastMonth[1])) {	//m2
						task.setM2(count);
					}else if(cr.get("mouth").equals(lastMonth[2])) {	//m3
						task.setM3(count);
					}
				}
			}
			msg = new Msg(1,task);
		}
		return msg;
	}
	
	@Override
	public int insert(TaskDTO dto){
		return taskMapper.insert(dto);
	}
	
	@Override
	public PageInfo<TaskTotal> selectTotal(TaskTotalDTO dto){
		//DownLoadUtil.set("TaskTotalDTO",dto);
		PageHelper.startPage(dto.getPageNumber(),dto.getPageSize());
		
		List<TaskTotal> list = taskMapper.selectForTotal(dto);
		PageInfo<TaskTotal> pageInfo = new PageInfo<TaskTotal>(list);
		return pageInfo;
	}
}
